package com.zh.blog.common.api;

import lombok.Data;

import static com.zh.blog.common.api.StatusCodeEnum.FAILED;
import static com.zh.blog.common.api.StatusCodeEnum.SUCCESS;

/**
 * 通用数据返回类
 * @author ZhengHao
 * Created At 2022/7/29.
 **/
@Data
public class Result<T> {

    /**
     * 返回状态
     */
    private Boolean flag;

    /**
     * 返回码
     */
    private Integer code;

    /**
     * 返回信息
     */
    private String message;

    /**
     * 返回数据
     */
    private T data;

    public static <T> Result<T> ok(){
        return restResult(true,null,SUCCESS.getCode(),SUCCESS.getDesc());
    }

    public static <T> Result<T> ok(T data){
        return restResult(true,data,SUCCESS.getCode(),SUCCESS.getDesc());
    }

    public static <T> Result<T> ok(T data,String message){
        return restResult(true,data,SUCCESS.getCode(),SUCCESS.getDesc());
    }

    public static <T> Result<T> fail(){
        return restResult(false,null,FAILED.getCode(),FAILED.getDesc());
    }

    public static <T> Result<T> fail(StatusCodeEnum statusCodeEnum){
        return restResult(false,null,statusCodeEnum.getCode(),statusCodeEnum.getDesc());
    }

    public static <T> Result<T> fail(String message){
        return restResult(false,message);
    }

    public static <T> Result<T> fail(T data){
        return restResult(false,data,FAILED.getCode(),FAILED.getDesc());
    }

    public static <T> Result<T> fail(T data, String message){
        return restResult(false, data, FAILED.getCode(),message);
    }

    public static <T> Result<T> fail(Integer code, String message){
        return restResult(false, null,code,message);
    }

    private static <T> Result<T> restResult(Boolean flag, String message){
        Result<T> result = new Result<>();
        result.setFlag(flag);
        result.setCode(flag ? SUCCESS.getCode() : FAILED.getCode());
        result.setMessage(message);
        return result;
    }

    private static <T> Result<T> restResult(Boolean flag, T data, Integer code, String message){
        Result result = new Result();
        result.setFlag(flag);
        result.setData(data);
        result.setCode(code);
        result.setMessage(message);
        return result;
    }
}